package com.imut.lagain.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.MemoryEntry;
import com.imut.lagain.service.IMemoryEntryService;
import com.imut.lagain.service.IFileUploadService;
import com.imut.lagain.util.JwtUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import jakarta.validation.constraints.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 记忆条目控制器
 */
@RestController
@RequestMapping("/api/memory-entries")
@RequiredArgsConstructor
@Validated
public class MemoryEntryController {
    private static final Logger log = LoggerFactory.getLogger(MemoryEntryController.class);

    private final IMemoryEntryService memoryEntryService;
    private final IFileUploadService fileUploadService;
    private final JwtUtil jwtUtil;

    /**
     * 根据胶囊ID获取记忆条目列表
     * @param authorization JWT令牌
     * @param capsuleId 胶囊ID
     * @param page 页码
     * @param size 每页大小
     * @param type 条目类型筛选
     * @return 条目列表
     */
    @GetMapping("/capsule/{capsuleId}")
    public ResponseEntity<Map<String, Object>> getEntriesByCapsule(
            @RequestHeader("Authorization") String authorization,
            @PathVariable Long capsuleId,
            @Min(value = 1, message = "页码必须大于0") @RequestParam(defaultValue = "1") int page,
            @Min(value = 1, message = "每页大小必须大于0") @Max(value = 100, message = "每页大小不能超过100") @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String type) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Page<MemoryEntry> entryPage;
            if (type != null && !type.isEmpty()) {
                entryPage = memoryEntryService.getEntriesByCapsuleIdAndType(capsuleId, type, page, size);
            } else {
                entryPage = memoryEntryService.getEntriesByCapsuleIdWithPage(capsuleId, page, size);
            }
            
            response.put("success", true);
            response.put("data", entryPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get entries by capsule", e);
            response.put("success", false);
            response.put("message", "获取记忆条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 创建文本记忆条目
     * @param authorization JWT令牌
     * @param request 创建请求
     * @return 创建结果
     */
    @PostMapping("/text")
    public ResponseEntity<Map<String, Object>> createTextEntry(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody CreateTextEntryRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            MemoryEntry entry = memoryEntryService.createTextEntry(
                    request.getCapsuleId(),
                    userId,
                    request.getContent()
            );
            
            if (entry != null) {
                response.put("success", true);
                response.put("data", entry);
                response.put("message", "文本条目创建成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "文本条目创建失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to create text entry", e);
            response.put("success", false);
            response.put("message", "创建文本条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 创建图片记忆条目
     * @param authorization JWT令牌
     * @param capsuleId 胶囊ID
     * @param file 图片文件
     * @param content 描述内容
     * @return 创建结果
     */
    @PostMapping("/image")
    public ResponseEntity<Map<String, Object>> createImageEntry(
            @RequestHeader("Authorization") String authorization,
            @RequestParam Long capsuleId,
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) String content) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "图片文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 上传文件
            Map<String, Object> uploadResult = fileUploadService.uploadImage(file, userId);
            if (!(Boolean) uploadResult.get("success")) {
                response.put("success", false);
                response.put("message", "图片上传失败: " + uploadResult.get("error"));
                return ResponseEntity.internalServerError().body(response);
            }
            
            String fileUrl = (String) uploadResult.get("url");
            
            MemoryEntry entry = memoryEntryService.createImageEntry(
                    capsuleId,
                    userId,
                    fileUrl,
                    content
            );
            
            if (entry != null) {
                response.put("success", true);
                response.put("data", entry);
                response.put("message", "图片条目创建成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "图片条目创建失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to create image entry", e);
            response.put("success", false);
            response.put("message", "创建图片条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 创建音频记忆条目
     * @param authorization JWT令牌
     * @param capsuleId 胶囊ID
     * @param file 音频文件
     * @param content 描述内容
     * @return 创建结果
     */
    @PostMapping("/audio")
    public ResponseEntity<Map<String, Object>> createAudioEntry(
            @RequestHeader("Authorization") String authorization,
            @RequestParam Long capsuleId,
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) String content) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "音频文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 上传文件
            Map<String, Object> uploadResult = fileUploadService.uploadAudio(file, userId);
            if (uploadResult == null || !Boolean.TRUE.equals(uploadResult.get("success"))) {
                response.put("success", false);
                response.put("message", "音频上传失败");
                return ResponseEntity.internalServerError().body(response);
            }
            String fileUrl = (String) uploadResult.get("url");
            if (fileUrl == null) {
                response.put("success", false);
                response.put("message", "音频上传失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
            MemoryEntry entry = memoryEntryService.createAudioEntry(
                    capsuleId,
                    userId,
                    fileUrl,
                    content
            );
            
            if (entry != null) {
                response.put("success", true);
                response.put("data", entry);
                response.put("message", "音频条目创建成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "音频条目创建失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to create audio entry", e);
            response.put("success", false);
            response.put("message", "创建音频条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 创建视频记忆条目
     * @param authorization JWT令牌
     * @param capsuleId 胶囊ID
     * @param file 视频文件
     * @param content 描述内容
     * @return 创建结果
     */
    @PostMapping("/video")
    public ResponseEntity<Map<String, Object>> createVideoEntry(
            @RequestHeader("Authorization") String authorization,
            @RequestParam Long capsuleId,
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) String content) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "视频文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 上传文件
            Map<String, Object> uploadResult = fileUploadService.uploadVideo(file, userId);
            if (uploadResult == null || !Boolean.TRUE.equals(uploadResult.get("success"))) {
                response.put("success", false);
                response.put("message", "视频上传失败");
                return ResponseEntity.internalServerError().body(response);
            }
            String fileUrl = (String) uploadResult.get("url");
            if (fileUrl == null) {
                response.put("success", false);
                response.put("message", "视频上传失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
            MemoryEntry entry = memoryEntryService.createVideoEntry(
                    capsuleId,
                    userId,
                    fileUrl,
                    content
            );
            
            if (entry != null) {
                response.put("success", true);
                response.put("data", entry);
                response.put("message", "视频条目创建成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "视频条目创建失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to create video entry", e);
            response.put("success", false);
            response.put("message", "创建视频条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新记忆条目
     * @param authorization JWT令牌
     * @param id 条目ID
     * @param request 更新请求
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateEntry(
            @RequestHeader("Authorization") String authorization,
            @PathVariable Long id,
            @Valid @RequestBody UpdateEntryRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = memoryEntryService.updateEntry(id, request.getContent());
            if (success) {
                response.put("success", true);
                response.put("message", "条目更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "条目更新失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to update entry", e);
            response.put("success", false);
            response.put("message", "更新条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新条目排序
     * @param authorization JWT令牌
     * @param id 条目ID
     * @param request 排序请求
     * @return 更新结果
     */
    @PutMapping("/{id}/sort")
    public ResponseEntity<Map<String, Object>> updateSortOrder(
            @RequestHeader("Authorization") String authorization,
            @PathVariable Long id,
            @Valid @RequestBody UpdateSortOrderRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = memoryEntryService.updateSortOrder(id, request.getSortOrder());
            if (success) {
                response.put("success", true);
                response.put("message", "排序更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "排序更新失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to update sort order", e);
            response.put("success", false);
            response.put("message", "更新排序失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 搜索记忆条目
     * @param authorization JWT令牌
     * @param keyword 搜索关键词
     * @param capsuleId 胶囊ID（可选）
     * @param page 页码
     * @param size 每页大小
     * @return 搜索结果
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchEntries(
            @RequestHeader("Authorization") String authorization,
            @NotBlank(message = "搜索关键词不能为空") @Size(min = 1, max = 100, message = "关键词长度必须在1-100之间") @RequestParam String keyword,
            @Min(value = 1, message = "胶囊ID必须大于0") @RequestParam(required = false) Long capsuleId,
            @Min(value = 1, message = "页码必须大于0") @RequestParam(defaultValue = "1") int page,
            @Min(value = 1, message = "每页大小必须大于0") @Max(value = 100, message = "每页大小不能超过100") @RequestParam(defaultValue = "20") int size) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            Page<MemoryEntry> entryPage = memoryEntryService.searchEntries(userId, keyword, capsuleId, page, size);
            
            response.put("success", true);
            response.put("data", entryPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to search entries", e);
            response.put("success", false);
            response.put("message", "搜索条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 根据时间范围获取记忆条目
     * @param authorization JWT令牌
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param page 页码
     * @param size 每页大小
     * @return 条目列表
     */
    @GetMapping("/time-range")
    public ResponseEntity<Map<String, Object>> getEntriesByTimeRange(
            @RequestHeader("Authorization") String authorization,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            Page<MemoryEntry> entryPage = memoryEntryService.getEntriesByTimeRange(userId, startTime, endTime, page, size);
            
            response.put("success", true);
            response.put("data", entryPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get entries by time range", e);
            response.put("success", false);
            response.put("message", "获取时间范围条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取包含文件的记忆条目
     * @param authorization JWT令牌
     * @param page 页码
     * @param size 每页大小
     * @return 条目列表
     */
    @GetMapping("/with-files")
    public ResponseEntity<Map<String, Object>> getEntriesWithFiles(
            @RequestHeader("Authorization") String authorization,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            Page<MemoryEntry> entryPage = memoryEntryService.getEntriesWithFiles(userId, page, size);
            
            response.put("success", true);
            response.put("data", entryPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Failed to get entries with files", e);
            response.put("success", false);
            response.put("message", "获取文件条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除记忆条目
     * @param authorization JWT令牌
     * @param id 条目ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteEntry(
            @RequestHeader("Authorization") String authorization,
            @PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = memoryEntryService.deleteEntry(id);
            if (success) {
                response.put("success", true);
                response.put("message", "条目删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "条目删除失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to delete entry", e);
            response.put("success", false);
            response.put("message", "删除条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 恢复已删除的记忆条目
     * @param authorization JWT令牌
     * @param id 条目ID
     * @return 恢复结果
     */
    @PutMapping("/{id}/restore")
    public ResponseEntity<Map<String, Object>> restoreEntry(
            @RequestHeader("Authorization") String authorization,
            @PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            if (!jwtUtil.validateToken(token)) {
                response.put("success", false);
                response.put("message", "Token无效");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = memoryEntryService.restoreEntry(id);
            if (success) {
                response.put("success", true);
                response.put("message", "条目恢复成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "条目恢复失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("Failed to restore entry", e);
            response.put("success", false);
            response.put("message", "恢复条目失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 创建文本条目请求DTO
     */
    @Data
    public static class CreateTextEntryRequest {
        @NotNull(message = "胶囊ID不能为空")
        @Min(value = 1, message = "胶囊ID必须大于0")
        private Long capsuleId;

        @NotBlank(message = "内容不能为空")
        @Size(min = 1, max = 2000, message = "内容长度必须在1-2000之间")
        private String content;
        
        public Long getCapsuleId() {
            return capsuleId;
        }
        
        public String getContent() {
            return content;
        }
        
        public void setCapsuleId(Long capsuleId) {
            this.capsuleId = capsuleId;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
    }

    /**
     * 更新条目请求DTO
     */
    @Data
    public static class UpdateEntryRequest {
        @NotBlank(message = "内容不能为空")
        @Size(min = 1, max = 2000, message = "内容长度必须在1-2000之间")
        private String content;
        
        public String getContent() {
            return content;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
    }

    /**
     * 更新排序请求DTO
     */
    @Data
    public static class UpdateSortOrderRequest {
        @NotNull(message = "排序值不能为空")
        @Min(value = 0, message = "排序值必须大于等于0")
        private Integer sortOrder;
        
        public Integer getSortOrder() {
            return sortOrder;
        }
        
        public void setSortOrder(Integer sortOrder) {
            this.sortOrder = sortOrder;
        }
    }
}